package com.xique.api.service.biz.service.impl;

import com.xique.api.api.domain.ApiThirdToken;
import com.xique.api.api.model.LoginApiThirdToken;
import com.xique.api.bean.request.ThirdAccountAddRequest;
import com.xique.api.service.biz.service.IApiThirdTokenBizService;
import com.xique.api.service.service.IApiThirdTokenService;
import com.xique.api.utils.AppUtils;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.web.domain.AjaxResult;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shd
 * @create 2022/2/24 13:59
 */
@Service
public class ApiThirdTokenBizServiceImpl implements IApiThirdTokenBizService {

    @Autowired
    private IApiThirdTokenService apiThirdTokenService;

    @Override
    public R<LoginApiThirdToken> getThirdAccount(String appId, String appSecret) {
        ApiThirdToken search = new ApiThirdToken();
        search.setAppId(appId);
        search.setAppSecret(appSecret);
        List<ApiThirdToken> list = apiThirdTokenService.selectApiThirdTokenList(search);
        if (CollectionUtils.isEmpty(list)) {
            return R.fail("未找到对应的账号信息");
        }
        ApiThirdToken token = list.get(0);

        LoginApiThirdToken loginApiThirdToken = new LoginApiThirdToken();
        loginApiThirdToken.setAppId(token.getAppId());
        loginApiThirdToken.setAccessToken(token.getAccessToken());
        loginApiThirdToken.setForeignId(token.getForeignId());
        loginApiThirdToken.setForeignType(token.getForeignType());
        loginApiThirdToken.setForeignName(token.getForeignName());
        loginApiThirdToken.setToken(token);


        return R.ok(loginApiThirdToken);
    }

    @Override
    public AjaxResult getAppIdAndAppSecret() {

        String appId = AppUtils.getAppId();
        ApiThirdToken search = new ApiThirdToken();
        search.setAppId(appId);
        List<ApiThirdToken> list = apiThirdTokenService.selectApiThirdTokenList(search);
        if (CollectionUtils.isNotEmpty(list)) {
            return AjaxResult.error("请重新生成");
        }
        String appSecret = AppUtils.getAppSecret(appId);

        Map<String, Object> map = new HashMap<>(2);
        map.put("appId", appId);
        map.put("appSecret", appSecret);

        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult addThirdAccount(ThirdAccountAddRequest request) {

        ApiThirdToken token = OrikaUtil.convert(request, ApiThirdToken.class);

        int count = apiThirdTokenService.insertApiThirdToken(token);
        if (count <= 0) {
            return AjaxResult.error("添加失败");
        }

        return AjaxResult.success("添加成功");
    }
}
